package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.ConfigEntity;
import com.chushouya.manager.dao.mapper.ConfigEntityMapper;
import com.chushouya.manager.dto.admin.config.ConfigQuery;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Repository
public class ConfigRepository extends BaseRepository<ConfigEntityMapper, ConfigEntity, Long> {

    public ConfigEntity selectOne(ConfigQuery query) {
        Example example = this.buildExample(query);
        return this.selectFirstOneByExample(example);
    }

    private Example buildExample(ConfigQuery query) {
        Example example = this.buildExample();
        if (Strings.isNotEmpty(query.getConfigName())) {
            example.and().andLike("configName",  Strings.format("%{}%", query.getConfigName()));
        }
        if (Strings.isNotEmpty(query.getConfigKey())) {
            example.and().andLike("configKey",  query.getConfigKey());
        }
        if (Strings.isNotEmpty(query.getConfigValue())) {
            example.and().andLike("configValue", Strings.format("%{}%", query.getConfigValue()));
        }
        if (Strings.isNotEmpty(query.getConfigType())) {
            example.and().andEqualTo("configType", query.getConfigType());
        }
        if (Objects.nonNull(query.getSystemConfig())) {
            example.and().andEqualTo("systemConfig", query.getSystemConfig());
        }
        if (Objects.nonNull(query.getIdNotEqualTo())) {
            example.and().andNotEqualTo("configId", query.getIdNotEqualTo());
        }
        example.orderBy("configId").desc();
        return example;
    }

    public PageResult<ConfigEntity> selectPageResult(ConfigQuery query) {
        Example example = this.buildExample(query);
        return this.selectPage(query.getPageRequest(), example);
    }

    public List<ConfigEntity> selectConfigList(ConfigQuery query) {
        Example example = this.buildExample(query);
        return this.selectByExample(example);
    }
}
